#!/usr/bin/env python
import sys

import numpy as N

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from plotDataClass import LPC
from matplotlib.lines import Line2D


def probeLPC(lpc):
    if type(lpc.get_ydict()) is dict:
        lpc_list = []
        for value in lpc.get_ydict().itervalues():
            lpc_list.append(getLPCScript(value))
        return lpc_list
    else:
        return getLPCScript(lpc)
        
def getLPCScript(lpc):
               
    lpc_dict = {}
    lpc_dict['xlabel'] = lpc.xlabel
    lpc_dict['ylabel'] = lpc.ylabel
    lpc_dict['xerr'] = lpc.xerr_label
    lpc_dict['yerr'] = lpc.yerr_label
    #lpc_dict['color'] = lpc.data.get_color() #this needs to be correct for the '#ff0000' fomat
    lpc_dict['linestyle'] = lpc.data.get_linestyle()
    lpc_dict['linewidth'] = lpc.data.get_linewidth()
    if lpc.data.get_marker() is None:
        lpc_dict['marker'] = lpc.data.get_marker()
        lpc_dict['markersize'] = lpc.data.get_markersize()
        lpc_dict['mcolor'] = lpc.data.get_markerfacecolor()
    
    return lpc_dict


def makeLPC(lpc_dict, dataDict = None):#make dataDict equal to self.parent.localVars.getPubDict() when parent exists
    varDict = dataDict
    if varDict:# is None:
        #if self.parent:
        #varDict = LOCALVARS.getPubDict() 
        #varDict = totaldict
        
        new_LPC = LPC()
        
        if type(varDict.get(lpc_dict.get('ylabel'))) is N.ndarray:
            y = varDict.get(lpc_dict.get('ylabel'))
        else:
            print "No Y-Array of that name exists...aborting"
            return 0
            
        if lpc_dict.get('xlabel') is None:
            x = N.arange(0,len(y))
            new_LPC.data.set_xdata(calcx)
        else:
           if type(varDict.get(lpc_dict.get('xlabel'))) is N.ndarray:
                x = varDict.get(lpc_dict.get('xlabel'))
                #print x
           else:
               print "No X-Array of that name exists defaulting to length of Y"
        
        data =[]
        new_LPC.data.set_ydata(y)
        new_LPC.data.set_xdata(x)
        
        new_LPC.xlabel = lpc_dict.get('xlabel')
        new_LPC.ylabel = lpc_dict.get('ylabel')        
        
        if lpc_dict.get('xerr'):
            if type(varDict.get(lpc_dict.get('xerr'))) is N.ndarray:
                new_LPC.set_xerr(varDict.get(lpc_dict.get('xerr')),  lpc_dict.get('xerr'))
        
        if lpc_dict.get('yerr'):
            if type(varDict.get(lpc_dict.get('yerr'))) is N.ndarray:
                new_LPC.set_yerr(varDict.get(lpc_dict.get('yerr')),  lpc_dict.get('yerr'))
        

    
        if lpc_dict.get('markersize'):
            new_LPC.data.set_markersize(lpc_dict.get('markersize'))
        if lpc_dict.get('marker'):
            new_LPC.data.set_marker(lpc_dict.get('marker'))
        if lpc_dict.get('linewidth'):
            new_LPC.data.set_linewidth(lpc_dict.get('linewidth'))
        if lpc_dict.get('linestyle'):
            new_LPC.data.set_linestyle(lpc_dict.get('linestyle'))
        if lpc_dict.get('color'):
            new_LPC.data.set_color( lpc_dict.get('color'))
        if lpc_dict.get('mcolor'):
            new_LPC.data.set_markerfacecolor(lpc_dict.get('mcolor'))
        
        return new_LPC

    else:
        print "No variable dictionary provided for makeLPC()"
        print "Aborting..."


##############The function below is old and has been updated in the main subplotGUI
##############The reason for doing this was to allow access to the primary variable dictionary
##############More elegant solutions are welcome
def lineplot(data = [],    
            xlabel = 'x',
            ylabel = 'y',
            xerr = None, 
            yerr = None, 
            color = None,
            mcolor = None, 
            linestyle = None,
            linewidth = None,
            marker = None,
            markersize = None,
            plotTitle = None,
            range_x = (None, None),
            range_y = (None, None),
            x_axlabel = None,
            y_axlabel = None,
            logx = False, 
            logy = False, 
            grids = False, 
            DATALIST = None):
                
    from Plot_Widget_Line2D import Plot_Widget    
    if len(data) != 0:
        new_LPC = LPC()
        if len(data) is 2:
            new_LPC.data = Line2D(data[0], data[1])
            new_LPC.data.set_picker(5)
        elif len(data) is 1:
            calcx = N.arange(0,len(data[0]))
            new_LPC.data = Line2D(calcx, data[0])
            new_LPC.data.set_picker(5)
        
        new_LPC.xlabel = xlabel
        new_LPC.ylabel = ylabel
        if type(range_x) is tuple:
            new_LPC.xscale = range_x
        elif type(range_x) is not tuple or None:
            print "range_x must be a tuple of min and max axis values"
        
        if type(range_y) is tuple:
            new_LPC.yscale = range_y
        elif type(range_y) is not tuple or None:
            print "range_y must be a tuple of min and max axis values"
            
        new_LPC.grids = grids
        new_LPC.plotTitle = plotTitle
        new_LPC.xtitle = x_axlabel
        new_LPC.ytitle = y_axlabel
        if markersize:
            new_LPC.data.set_markersize(markersize)
        if marker:
            new_LPC.data.set_marker(marker)
        if linewidth:
            new_LPC.data.set_linewidth(linewidth)
        if linestyle:
            new_LPC.data.set_linestyle(linestyle)
        if color:
            new_LPC.data.set_color(color)
        if mcolor:
            new_LPC.data.set_markerfacecolor(mcolor)
    
    plot = Plot_Widget()
    try:
        if new_LPC:
            plot.initialize_plot(new_LPC)
    except:
        pass
    if DATALIST:
        varDict = LOCALVARS.getPubDict()
        for line in DATALIST:
            plot.initialize_plot(makeLPC(line, varDict))
    plot.show()
    
if __name__ == "__main__":
    from Plot_Widget_Line2D import Plot_Widget
    app = QApplication(sys.argv)
    x = N.arange(0,30, N.random.random())
    y = N.cos(x-N.random.random())
    y2 = N.sin(x-N.random.random())
    y3 = 2*N.sin(x-N.random.random())
    y4 = 2*N.cos(x-N.random.random())
    y5 = 3*N.sin(x-N.random.random())
    y6 = 4*N.cos(x-N.random.random())
    y7 = 5*N.sin(x-N.random.random())
    y8 = 6*N.cos(x-N.random.random())
    test = 7*N.cos(x-N.random.random())
    dummyDict = {'None':None}
    xdict = {'x':x}
    #xdict = {'None':None}
    #ydict = {'y':y}
    ydict = {'y2':y2, 'y3':y3}
    #ydict = {'y2':y2, 'y3':y3, 'y4':y4, 'y5':y5, 'y6':y6,'y7':y7, 'y8':y8}
    totaldict = {'x':x,'y':y,'y2':y2, 'y3':y3, 'y4':y4, 'y5':y5, 'y6':y6,'y7':y7, 'y8':y8,  'test':test}
    data2plot = LPC([xdict,ydict])
    
    #print type(data2plot.data)
    #lpcscript = getLPCScript(data2plot)
    lpcscript = probeLPC(data2plot)
    #print lpcscript
    #constructLPC = makeLPC(lpcscript, totaldict)
    #print constructLPC
    
    print "lineplot(DATALIST = %s)" % lpcscript
    test_list = [{'markersize': 6, 'mcolor': 'b', 'ylabel': 'y8', 'marker': 'None', 'xlabel': 'x', 'linewidth': 1.0, 'linestyle': '-'}, {'markersize': 6, 'mcolor': 'b', 'ylabel': 'y3', 'marker': 'None', 'xlabel': 'x', 'linewidth': 1.0, 'linestyle': '-'}, {'markersize': 6, 'mcolor': 'b', 'ylabel': 'y2', 'marker': 'None', 'xlabel': 'x', 'linewidth': 1.0, 'linestyle': '-'}, {'markersize': 6, 'mcolor': 'b', 'ylabel': 'y5', 'marker': 'None', 'xlabel': 'x', 'linewidth': 1.0, 'linestyle': '-'}, {'markersize': 6, 'mcolor': 'b', 'ylabel': 'y4', 'marker': 'None', 'xlabel': 'x', 'linewidth': 1.0, 'linestyle': '-'}, {'markersize': 6, 'mcolor': 'b', 'ylabel': 'y7', 'marker': 'None', 'xlabel': 'x', 'linewidth': 1.0, 'linestyle': '-'},  {'markersize': 6, 'mcolor': 'b', 'ylabel': 'y6', 'marker': 'None', 'xlabel': 'x', 'linewidth': 1.0, 'linestyle': '-'}, {'markersize': 6, 'mcolor': 'b', 'ylabel': 'test', 'marker': 'None', 'xlabel': 'x', 'linewidth': 1.0, 'linestyle': '-'}]    
    #print type(test_list)
    #print type(lpcscript)
    #lineplot(DATALIST = constructLPC)
    lineplot(DATALIST = test_list)

    #plot = Plot_Widget(data2plot)
    #plot = Plot_Widget()
    #plot.show()
    sys.exit(app.exec_())
